﻿using Autofac;
using DataCenter.IDataProvider;
using DataCenter.Service.Implementations;
using DataCenter.Service.Interfaces;
using System.Reflection;

namespace DataCenter.App
{
    public class DataCenterModule:Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            string[] codeProviders = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "//CodeProvider");
            foreach (string privoder in codeProviders)
            {
                var codeproviderAssembly = Assembly.LoadFile(privoder);
                Console.WriteLine("***********************************");
                Console.WriteLine(codeproviderAssembly.FullName);
                foreach (var type in codeproviderAssembly.GetTypes())
                {
                    Console.WriteLine(  type.FullName);

                    if (type.Name.EndsWith("Provider") &&  !type.GetCustomAttributes().Any(attr => attr.GetType() == typeof(UnInstanceAttribute)))
                    {
                        Console.WriteLine("this is " + type.ToString());
                        //builder.RegisterAssemblyTypes(codeproviderAssembly).Where(item => item.Name.EndsWith("Provider")).As<ICodeProvider>().InstancePerDependency();
                        builder.RegisterType(type).AsImplementedInterfaces().InstancePerDependency();
                    }
                    else
                    {
                    }
                }
                Console.WriteLine("***********************************");
                if (!codeproviderAssembly.GetCustomAttributes(false).Any(attr=> attr.GetType() == typeof(UnInstanceAttribute)))
                {
                   // builder.RegisterAssemblyTypes(codeproviderAssembly).Where(item => item.Name.EndsWith("Provider")).As<ICodeProvider>().InstancePerDependency();
                }
            }
             var serviceAssembly = Assembly.Load("DataCenter.Service");
             builder.RegisterAssemblyTypes(serviceAssembly)
            .Where(
            
                 t => {
                     return t.Name.EndsWith("Service");
                     }
                 
                 )
            .AsImplementedInterfaces().InstancePerDependency();


            var reposirotyAssembly = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + "DataCenter.MemoryRepository.dll");
            builder.RegisterAssemblyTypes(reposirotyAssembly)
           .Where(
                t => t.Name.EndsWith("Repository")
                )
           .AsImplementedInterfaces().InstancePerDependency();

        }
    }
}
